#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdalign.h>
#include <unistd.h>

const std::string gpath = "/home/swb";
int gprojId = 0x6666;
int gshmsize = 4096;
mode_t gmode = 0600;

//将十进制的key转化为十六进制，方便查看
std::string ToHex(key_t k)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%x", k);
    return buffer;
}

class ShareMemory
{
private:
    //创建和获取一块共享内存的代码重复度高，提取成一个子方法
    void CreateShmHelper(int shmflg)
    {
        _key = ::ftok(gpath.c_str(), gprojId);
        if(_key < 0)
        {
            std::cerr << "ftok error" << std::endl;
            return ;
        }
        _shmid = ::shmget(_key, gshmsize, shmflg);
        if(_shmid < 0)
        {
            std::cerr << "shmget error" << std::endl;
            return ;
        }
        std::cout << "shmid: " << _shmid << std::endl;
    }
public:
    ShareMemory()
        :_shmid(-1),
         _key(0),
         _addr(nullptr)
    {}

    ~ShareMemory(){}

    void CreateShm()
    {
        if(_shmid == -1)
        {
            CreateShmHelper(IPC_CREAT | IPC_EXCL | gmode);
        }
    }

    void GetShm()
    {
        CreateShmHelper(IPC_CREAT);
    }

    void AttachShm()
    {
        _addr = shmat(_shmid, nullptr, 0);
        if((long long)_addr == -1) //longlong 是因为当前是64位系统，地址占八字节
        {
            std::cout << "attach error" << std::endl;
        }
    }

    void DetachShm()
    {
        if(_addr != nullptr)
            ::shmdt(_addr);
        std::cout << "detach done" <<std::endl;
    }

    void DeleteShm()
    {
        shmctl(_shmid, IPC_RMID, nullptr);
    }

    void* GetAddr()
    {
        return _addr;
    }

private:
    int _shmid;
    key_t _key;
    void* _addr;
};

ShareMemory shm;
